package com.wtpaint.lib.skin;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.v4.view.LayoutInflaterCompat;
import android.view.LayoutInflater;

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * Created by leoxu on 2018/11/18.
 */

public class SkinActivityLifecycle implements Application.ActivityLifecycleCallbacks {
    HashMap<Activity, ZeusSkinFactory> mLayoutFactoryMap = new HashMap<>();

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        LayoutInflater inflater = LayoutInflater.from(activity);

        /**
         * 参看代码 setFactory
         * if (mFactorySet) {
         throw new IllegalStateException("A factory has already been set on this LayoutInflater");
         }
         */
        try {
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(inflater, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ZeusSkinFactory factory = new ZeusSkinFactory();
        LayoutInflaterCompat.setFactory2(inflater, factory);
        //注册观察者
        ZeusSkinManager.getInstance().addObserver(factory);
        mLayoutFactoryMap.put(activity, factory);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        ZeusSkinFactory skinLayoutFactory = mLayoutFactoryMap.remove(activity);
        ZeusSkinManager.getInstance().deleteObserver(skinLayoutFactory);
    }
}
